﻿using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Core.Utility.Helper
{
    /// <summary>
    /// 短链接助手类
    /// <para>当前局限于通过雪花Id生成短连接的场景下使用</para>
    /// </summary>
    public static class ShortLinkHelper
    {
        private const string base62Characters = "mno0123abcdefghijklpqrstuvwxyz456ABCDEFGHIJKLMNOPQRSTUVWXYZ789";
        static int base62 = base62Characters.Length;


        /// <summary>
        /// 编码为Base62
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static string LongToShortParam(long? number)
        {
            StringBuilder sbRes = new StringBuilder();
            long lNumber = number ?? 0;
            do
            {
                sbRes.Append(base62Characters[(int)(lNumber % base62)]);
                lNumber /= base62;
            } while (lNumber > 0);
            return sbRes.ToString();
        }

        /// <summary>
        /// 通过Base62字符串解码
        /// </summary>
        /// <param name="shortParam"></param>
        /// <returns></returns>
        public static long? ShortParamToLong(string? shortParam)
        {
            long? number = 0;
            string sShortParam = shortParam ?? "";
            //if (sShortParam.Length > 1)
            //{
            //    //余值作为起始值
            //    number = base62Characters.IndexOf(sShortParam[0]);
            //    sShortParam = sShortParam.Substring(1);
            //}
            if (sShortParam.Length > 0)
            {
                char[] charArray = sShortParam.ToArray();
                Array.Reverse(charArray);
                sShortParam = string.Join("", charArray);
            }
            foreach (char c in sShortParam)
            {
                number = number * base62 + base62Characters.IndexOf(c);
            }
            return number;
        }
    }
}
